package pers.crayon.baseprogram.util;

import cn.hutool.core.lang.Assert;
import lombok.experimental.UtilityClass;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求工具类，以静态资源方式保证可用
 * 可以在这里写方法 getAttribute 获取 约定的用户信息
 *
 * @author roamay.com
 * @since 2021/2/19 16:48
 */
@UtilityClass
public class RequestUtil {

    /**
     * 获取当前请求的request。是线程安全的
     *
     * @return
     */
    public HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Assert.isNull(attributes);
        return attributes == null ? null : attributes.getRequest();
    }

    /**
     * 获得request中的属性值
     *
     * @param name 名称
     * @return
     */
    public Object getAttribute(String name) {
        HttpServletRequest currentRequest = getCurrentRequest();
        Assert.isNull(currentRequest);
        return currentRequest.getAttribute(name);
    }
}